$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

var subArray =new Array();
var idArray=new Array();
var qIdArray=new Array();
var memoArray =new Array();

$(document).ready(function () {
    var requestId=$('#requestId').val();
    var quotationId=$('#quotationId').val();
    var subtotalTaxed=$('#subtotalTaxed').val();
    var biddingMethod=$('#biddingMethod').val();//竞价方式0-单价，1-总价
    var rtype=$('#rtype').val();
    var colModel;
    if (biddingMethod == 0) {//不可编辑
        colModel = [
            {label: '报价物料行ID', name: 'id', index: 'ID', hidden: true},
            {label: '询单物料行ID', name: 'requestItemId', index: 'REQUEST_ITEM_ID', hidden: true},
            {label: '物料代码', name: 'materialNo', index: 'MATERIAL_NO', align: 'center'},
            {label: '物料名称', name: 'materialName', index: 'MATERIAL_NAME', align: 'center'},
            {label: '型规', name: 'character', index: 'CHARACTER', align: 'center'},
            {label: '数量', name: 'requestAmount', index: 'REQUEST_AMOUNT', align: 'center'},
            {label: '单位', name: 'unit', index: 'UNIT', align: 'center'},
            {label: '要求交货期', name: 'requestDeliveryDate', index: 'REQUEST_DELIVERY_DATE', formatter: 'date', formatoptions: {srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d'}},
            {label: '单价', name: 'unitPriceTaxed', index: 'UNIT_PRICE_TAXED', align: 'center'},
            {label: '小计', name: 'subtotalTaxed', index: 'SUBTOTAL_TAXED', align: 'center'},
            {label: '备注', name: 'memo', index: 'MEMO', align: 'center'},
            {label: '我的出价', name: 'mySubtotalTaxed', index: 'MY_SUBTOTAL_TAXED', align: 'center',formatter: actFormatter}
        ];
    } else {
        if (rtype != 10) { //可编辑
            colModel = [
                {label: '询单物料行ID', name: 'id', index: 'ID', hidden: true},
                {label: '询单物料行ID', name: 'requestItemId', index: 'REQUEST_ITEM_ID', hidden: true},
                {label: '物料代码', name: 'materialNo', index: 'MATERIAL_NO', align: 'center'},
                {label: '物料名称', name: 'materialName', index: 'MATERIAL_NAME', align: 'center'},
                {label: '型规', name: 'character', index: 'CHARACTER', align: 'center'},
                {label: '数量', name: 'requestAmount', index: 'REQUEST_AMOUNT', align: 'center'},
                {label: '单位', name: 'unit', index: 'UNIT', align: 'center'},
                {label: '要求交货期', name: 'requestDeliveryDate', index: 'REQUEST_DELIVERY_DATE', formatter: 'date', formatoptions: {srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d'}},
                {label: '单价', name: 'perPrice', index: 'PER_PRICE', align: 'center'},
                {label: '小计', name: 'subtotal', index: 'SUBTOTAL', editable: true, align: 'center', editrules: {required: true}, cellEdit: true},
                {label: '备注', name: 'memo', index: 'MEMO', editable: true, align: 'center', cellEdit: true}
            ];
        } else { //不可编辑
            colModel = [
                {label: '询单物料行ID', name: 'id', index: 'ID', hidden: true},
                {label: '询单物料行ID', name: 'requestItemId', index: 'REQUEST_ITEM_ID', hidden: true},
                {label: '物料代码', name: 'materialNo', index: 'MATERIAL_NO', align: 'center'},
                {label: '物料名称', name: 'materialName', index: 'MATERIAL_NAME', align: 'center'},
                {label: '型规', name: 'character', index: 'CHARACTER', align: 'center'},
                {label: '数量', name: 'requestAmount', index: 'REQUEST_AMOUNT', align: 'center'},
                {label: '单位', name: 'unit', index: 'UNIT', align: 'center'},
                {label: '要求交货期', name: 'requestDeliveryDate', index: 'REQUEST_DELIVERY_DATE', formatter: 'date', formatoptions: {srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d'}},
                {label: '单价', name: 'unitPriceTaxed', index: 'UNIT_PRICE_TAXED', align: 'center'},
                {label: '小计', name: 'subtotalTaxed', index: 'SUBTOTAL_TAXED',align: 'center'},
                {label: '备注', name: 'memo', index: 'MEMO', align: 'center'}
            ];
        }
    }

        RFQ.jqGrid('#jqGrid').init({
        url:ctx+'/weizhongbiao/rfqQuotationHisotryList',
        colModel: colModel,
        rownumbers: true,
        sortname: 'rri.seq',
        sortorder: 'asc',
        pager: "#jqGridPager",
        cellEdit: true,
        cellsubmit: 'clientArray',
        //点击变成可编辑状态方法
           /* ondblClickRow: function(rowid){
              //if ((type!=10)){...}; 未结束(两项可编辑)
                console.log(rowid);
                if(rtype!=10) {
                        if (rowid && rowid != lastsel) {
                            var rowData = $("#jqGrid").jqGrid("getRowData", rowid);
                            console.log(rowData);
                            var qId = rowData.id;
                            $('#jqGrid').jqGrid('saveRow', lastsel);
                            $('#jqGrid').jqGrid('editRow', rowid, true);
                            lastsel = rowid;
                        }
                 }
            },*/
            /*保存单元格内容后触发事件*/
            afterSaveCell:function(rowid,cellname,value,iRow,iCol){
                    //console.log("111111111"+rowid);
                    var rowData = $("#jqGrid").jqGrid("getRowData", rowid);
                    var subtotalTaxedValue = rowData.subtotalTaxed;
                    var amount = rowData.requestAmount;
                    if(subtotalTaxedValue !=null&&subtotalTaxedValue !="") {
                        if (!isNaN(subtotalTaxedValue)) {
                            var prePrice = (subtotalTaxedValue / amount).toFixed(4);
                            $("#jqGrid").setRowData(rowid,{unitPriceTaxed:prePrice});
                        } else {
                            $("#jqGrid").setRowData(rowid,{subtotalTaxed:""});
                            RFQ.error("小计不能为非数字！");
                        }
                    }
            },

            onPaging:function(pgButton){
                importValues();
                $("#jqGrid").jqGrid("setGridParam",{
                    postData:
                        {subtotalTaxed:JSON.stringify(subArray),
                        requestItemId:JSON.stringify(idArray),
                        id:JSON.stringify(qIdArray),
                        memo:JSON.stringify(memoArray)},
                      'biddingMethod':biddingMethod
                })
            },
            postData:{
                'requestId':requestId,
                'quotationId':quotationId,
                'biddingMethod':biddingMethod
            }

            //设置不显示水平滚动条（可用）
           /* gridComplete: function () {
                function removeHorizontalScrollBar() {
                    $("div.ui-state-default.ui-jqgrid-hdiv.ui-corner-top").css("width", parseInt($("div.ui-state-default.ui-jqgrid-hdiv.ui-corner-top").css("width")) + 1 + "px");
                    $("#jqGridTable").closest(".ui-jqgrid-bdiv").css("width", parseInt($("#jqGridTable").closest(".ui-jqgrid-bdiv").css("width")) + 1 + "px");
                }
                removeHorizontalScrollBar();
            }*/

    });

    //判断是否隐藏“我的出价”(表格列隐藏了但依旧占用空间)
    /*if(biddingMethod==1){
     $("#jqGridTable").setGridParam().hideCol("mySubtotalTaxed").trigger("reloadGrid");
     }*/

   //判断提交|关闭按钮是否显示,新增附件是否可用
    if (biddingMethod == 0) {//按物料竞价时，无需补填
        $("#buttonDIV").css('display','none');//无需显示提交|关闭按钮
        $("#addAttachments").attr("disabled", true);//补填明细附件不可用
        $("#desc").show();//显示未中标说明
    } else {
        if (rtype != 10) {
            $("#buttonDIV").css('display','block');
            $("#addAttachments").attr("disabled", false);
            $("#desc").hide();//是否显示未中标说明
        } else {
            $("#buttonDIV").css('display','none');
            $("#addAttachments").attr("disabled", true);
            $("#desc").show();//是否显示未中标说明
        }
    }
});

/*cellvalue：要被格式化的值
 options：对数据进行格式化时的参数设置，格式为：
 { rowId: rid, colModel: cm}
 rowObject：行数据*/
function actFormatter(cellvalue, options, rawObject) {
    var detailBtn = '<span class="ml5"><a class="blue" onclick="showMap(\'' +rawObject.requestItemId+'\',\''+rawObject.materialName+ '\')">查看</a></span>';
    return detailBtn;
}

//绑定提交按钮
function submitSave(){
    var biddingMethod=$('#biddingMethod').val();
    var requestId=$('#requestId').val();
    var quotationId=$('#quotationId').val();
    var subtotalTaxed=$('#subtotalTaxed').val();
    importValues();
    $.ajax({
        url: ctx+'/weizhongbiao/getXJSum',
        data:{
            'requestId':requestId,
            'quotationId':quotationId,
            'subtotalTaxed':JSON.stringify(subArray),
            'requestItemId':JSON.stringify(idArray),
            'id':JSON.stringify(qIdArray),
            'memo':JSON.stringify(memoArray),
            'biddingMethod':biddingMethod
        },
        dataType: "json",
        success:function(data){
            if (data == subtotalTaxed){
                RFQ.info("提交保存成功!");
                location.href = ctx+"/rfqQuotation/init";
            } else {
                RFQ.error("提交失败，合价小计应与竞价金额相等！");
            }

        },
        error:function (data) {
            RFQ.error("提交保存失败!")
        }
    })
}

function importValues(){
    var ids = $("#jqGrid").jqGrid('getDataIDs');
    subArray = [];
    idArray= [];
    qIdArray=[];
    memoArray=[];
    for(var i=0;i<ids.length;i++){
        var datas = $("#jqGrid").jqGrid("getRowData", ids[i]);
        //$("#"+(i+1)+"_subtotalTaxed").val()!=undefined---input框
        if($("#"+(i+1)+"_subtotal").val()!=undefined){
            var a=$("#"+(i+1)+"_subtotal").val();
            subArray.push(a);
            memoArray.push(datas.memo);
        }else if ($("#"+(i+1)+"_memo").val()!=undefined){
            var b=$("#"+(i+1)+"_memo").val();
            subArray.push(datas.subtotal);
            memoArray.push(b);
        }else{
            subArray.push(datas.subtotal);
            memoArray.push(datas.memo);
        }
        idArray.push(datas.requestItemId);
        qIdArray.push(datas.id);
    };
}

showMap=function (requestItemId,name) {
    $.ajax({
        url:"WLQuotation",
        type:"POST",
        data:{
            requestId:$("#requestId").val(),
            requestItemId:requestItemId
        },
        datatype:'json',
        success: function (data) {
            var dataJson=eval("("+data+")");
            $("#materialName").html(name);
            $("#myModal19").modal('show');
            setEchat(dataJson.moneyList);
        },
        error: function () {
            $.zui.messager.show('链接失败！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        }
    });
}

showMap2=function(){
    $.ajax({
        type: "POST",
        url:ctx+'/weizhongbiao/quateOffer',
        data: {requestId: $("#requestId").val(),},
        datatype: 'json',
        success: function (data) {
            var dataJson = eval("(" + data + ")");
            $("#myModal20").modal('show');
            setEchat(dataJson.moneyList);
        },
        error: function () {
            $.zui.messager.show('链接失败！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        }
    })
}

function setEchat(moneyList){
   var biddingMethod = $('#biddingMethod').val();
    var myChart;
    // 基于准备好的dom，初始化echarts图表
    if(biddingMethod == 0){
         myChart = echarts.init(document.getElementById('mainChart'));
    }else{
         myChart = echarts.init(document.getElementById('mainChart1'));
    }
    var option=optionTemptale;
    // 为echarts对象加载数据
    myChart.setOption(convertData(moneyList,option));
}